package com.paoge.generator.service;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.paoge.generator.dao.db.Dm7GeneratorDao;
import com.paoge.generator.dao.db.GeneratorDao;
import com.paoge.generator.dao.db.MySQLGeneratorDao;
import com.paoge.generator.dao.db.OracleGeneratorDao;
import com.paoge.generator.dao.db.PostgreSQLGeneratorDao;
import com.paoge.generator.dao.db.SQLServerGeneratorDao;
import com.paoge.generator.utils.GenUtils;
import com.paoge.generator.utils.PageUtils;
import com.paoge.generator.utils.Query;
import com.paoge.generator.utils.RRException;

@Service
public class SysGeneratorService {

	public static String dbType;

	@Autowired
	private MySQLGeneratorDao mySQLGeneratorDao;
	@Autowired
	private OracleGeneratorDao oracleGeneratorDao;
	@Autowired
	private SQLServerGeneratorDao sqlServerGeneratorDao;
	@Autowired
	private PostgreSQLGeneratorDao postgreSQLGeneratorDao;
	@Autowired
	private Dm7GeneratorDao dm7GeneratorDao;

	@Primary
	public GeneratorDao getGeneratorDao() {
		if ("mysql".equalsIgnoreCase(dbType)) {
			return mySQLGeneratorDao;
		} else if ("oracle".equalsIgnoreCase(dbType)) {
			return oracleGeneratorDao;
		} else if ("sqlserver".equalsIgnoreCase(dbType)) {
			return sqlServerGeneratorDao;
		} else if ("postgresql".equalsIgnoreCase(dbType)) {
			return postgreSQLGeneratorDao;
		} else if ("dm7".equalsIgnoreCase(dbType)) {
			return dm7GeneratorDao;
		} else {
			throw new RRException("不支持当前数据库：" + dbType);
		}
	}

	public PageUtils queryList(Query query) {
		Page<?> page = PageHelper.startPage(query.getPage(), query.getLimit());

		List<Map<String, Object>> list = getGeneratorDao().queryList(query);

		return new PageUtils(list, (int) page.getTotal(), query.getLimit(), query.getPage());
	}

	public Map<String, String> queryTable(String tableName) {
		return getGeneratorDao().queryTable(tableName);
	}

	public List<Map<String, String>> queryColumns(String tableName) {
		return getGeneratorDao().queryColumns(tableName);
	}

	public byte[] generatorCode(String[] tableNames) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ZipOutputStream zip = new ZipOutputStream(outputStream);

		for (String tableName : tableNames) {
			// 查询表信息
			Map<String, String> table = queryTable(tableName);
			// 查询列信息
			List<Map<String, String>> columns = queryColumns(tableName);
			// 生成代码
			GenUtils.generatorCode(table, columns, zip);
		}
		IOUtils.closeQuietly(zip);
		return outputStream.toByteArray();
	}
}
